<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
class Auth {
    private $rpx_api_key = 'your RPX key';
    private $site_name = 'confab';
    private $rpx_auth_url = 'https://rpxnow.com/api/v2/auth_info';
    private $http_port = null;
    private $token_url = null;
    

    public function  __construct() {
	$this->http_port = $_SERVER['SERVER_PORT'] == '80' ? '' : ':'.$_SERVER['SERVER_PORT'];
	$this->token_url = 'http://' . $_SERVER['SERVER_NAME'] . $this->http_port . $_SERVER['SCRIPT_NAME'];
    }

    public function login($login_token) {
	$post_data = array(
	    'token' => $login_token,
	    'apiKey' => $this->rpx_api_key,
	    'format' => 'json'
	);
	$login_result = $this->communicate($post_data);
	return (isset($login_result['stat']) && $login_result['stat'] == 'ok') ? $login_result : false;
    }

    public function login_link($link_label='Sign In') {
	$token_url = urlencode($this->token_url);
	return "<a class=\"rpxnow\" href=\"https://{$this->site_name}.rpxnow.com/openid/v2/signin?token_url={$token_url}\">{$link_label}</a>";
    }
    public function token_url() {
	return $this->token_url;
    }

    private function communicate($post_data) {
	// make the api call using libcurl
	$curl = curl_init();
	curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($curl, CURLOPT_URL, $this->rpx_auth_url);
	curl_setopt($curl, CURLOPT_POST, true);
	curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);
	curl_setopt($curl, CURLOPT_HEADER, false);
	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
	$raw_json = curl_exec($curl);
	curl_close($curl);
	$decoded_json = json_decode($raw_json, true);
	$decoded_json['raw_json']=$raw_json;
	return $decoded_json;
    }
}
